from rest_framework.serializers import ModelSerializer
from .template import Template
from .material import MaterialCategory, MaterialTag
from .data import DataMeta, DataContent
from .dataset import DataSet
from rest_framework import serializers
from apps.storage.utils.serializers.json import JSONSerializer
from rest_framework.response import Response
import json
import logging

logger = logging.getLogger('django')


class TemplateSerializer(ModelSerializer):
    category_name = serializers.SerializerMethodField()

    class Meta:
        model = Template
        fields = ('id', 'title', 'category', 'category_name','author',
                  'abstract', 'ref_count', 'pub_date', 'published',
                  'content')

    def get_category_name(self, obj):
        try:
            ca = MaterialCategory.objects.get(pk=obj.category.id)
            return ca.name_zh
        except Exception:
            return None


class MaterialCategorySerializer(ModelSerializer):
    pid = serializers.IntegerField(source='parent_id')

    class Meta:
        model = MaterialCategory
        fields = ('id', 'pid', 'level', 'name_zh', 'name_en', 'leaf')


class MaterialTagSerializer(ModelSerializer):
    class Meta:
        model = MaterialTag
        fields = ('name', 'count')


class DataMetaSerializer(ModelSerializer):
    keyword = serializers.ListField(source='keywords', required=False)
    content = serializers.SerializerMethodField()
    template = serializers.SerializerMethodField()
    category_name = serializers.SerializerMethodField()

    class Meta:
        model = DataMeta
        fields = ('id', 'title', 'category', 'category_id', 'category_name', 'source',
                  'tid', 'keyword', 'content', 'doi', 'score',
                  'downloads', 'views', 'abstract', 'purpose', 'author',
                  'add_time', 'template')

    def get_content(self, obj):
        try:
            # dc = DataContent.objects.get(pk=obj.dc_id).to_json()
            # content = json.loads(dc)
            # content['_id'] = content['_id']['$oid']
            t = Template.objects.get(pk=obj.tid)
            js = JSONSerializer(t)
            r = js.get_serialized_obj(obj)
            return r['content']
        except Exception as ex:
            logger.info(ex)
            return {}

    def get_template(self, obj):
        template = Template.objects.get(pk=obj.tid)
        serializer = TemplateSerializer(template)
        return serializer.data

    def get_category_name(self, obj):
        try:
            ca = MaterialCategory.objects.get(pk=obj.category.id)
            return ca.name_zh
        except Exception:
            return None


class DataSetSerializer(ModelSerializer):
    class Meta:
        model = DataSet
        fields = ('id', 'title', 'author', 'purpose', 'ref_count',
                  'views', 'file', 'rows', 'cols', 'indexs', 'downloads')


def get_iter_content(dc_id):
    print(dc_id)
    dc = DataContent.objects.get(pk=dc_id).to_json()
    content = json.loads(dc)
    content['_id'] = content['_id']['$oid']
    test = {}
    for item in content:
        if type(content[item]) == type(test) and '$oid' in content[item]:
            content[item] = get_iter_content(content[item]['$oid'])
    print(content)
    return content
